﻿/*
 * Created by SharpDevelop.
 * User: christophe
 * Date: 7/09/2011
 * Time: 21:45
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Linq.Expressions;
using System.Windows.Forms;

using MetaVideoEditorEvolved.UI.Entity;

namespace MetaVideoEditorEvolved.UI.Helper
{
	/// <summary>
	/// Description of ConverterHelper.
	/// </summary>
	public static class ConverterHelper
	{
		internal static List<Entity.MediaItemBaseEntity> ConvertItemCollection(mveEngine.ItemCollection itemCollection)
		{
			var mediaItems = new List<Entity.MediaItemBaseEntity>();
			
			foreach (var item in itemCollection.MainNodes) {
				mediaItems.Add(CreateMediaItem(item));
			}
			
			return mediaItems;
		}
		
		internal static Entity.MediaItemBaseEntity FindElementInTree(List<Entity.MediaItemBaseEntity> mediaItems, Guid id)
		{
			
			foreach (var element in mediaItems) {
				var file = element as Entity.FileMediaElement;
				MediaItemBaseEntity found = null;
				
				if (file!=null) {
					if (file.Id.ToString() == id.ToString()) {
						return file;
					}
					
					var serie = element as SerieMediaItem;
					
					if (serie!=null) {
						found = FindElementInTree(serie.Seasons.Cast<Entity.MediaItemBaseEntity>().ToList(),id);
						
						if (found!=null) {
							return found;
						}
					}
					
					var season = element as SeasonMediaItem;
					
					if (season!=null) {
						found = FindElementInTree(season.Episodes.Cast<Entity.MediaItemBaseEntity>().ToList(),id);
						
						if (found!=null) {
							return found;
						}
					}
				}
				else
				{
					var folder = element as FolderMediaItem;
					found = FindElementInTree(folder.ContentItems.Cast<Entity.MediaItemBaseEntity>().ToList(),id);
					
					if (found!=null) {
						return found;
					}
				}
			}
			
			return null;
		}
		
		public static bool RemoveMediaFromTree(ObservableCollection<Entity.MediaItemBaseEntity> mediaItems ,Entity.MediaItemBaseEntity mediaToRemove, MediaItemBaseEntity parent)
		{
			UI.Entity.MediaItemBaseEntity lastParent=null;
			
			for (int i = 0; i < mediaItems.Count; i++) {
				var element  = mediaItems[i];
				if(parent==null)
				{
					lastParent = element;
				}
				else
				{
					lastParent = parent;
				}
				
				var folder = element as FolderMediaItem;
				if (folder!=null) {
					if (folder == mediaToRemove) {
						var folderParent = lastParent as FolderMediaItem;
						
						folderParent.ContentItems.Remove(folder);
						return true;
					}
					
					if (RemoveMediaFromTree(folder.ContentItems, mediaToRemove, folder)) {
						return true;
					}
				}
				
				var movie = element as MovieMediaItem;
				if (movie!=null) {
					if (movie==mediaToRemove) {
						var folderParent = lastParent as FolderMediaItem;
						folderParent.ContentItems.Remove(movie);
					}
				}
				
				var serie = element as Entity.SerieMediaItem;
				if (serie!=null) {
					if (serie == mediaToRemove) {
						var folderParent = lastParent as FolderMediaItem;
						
						folderParent.ContentItems.Remove(serie);
						return true;
					}
					
					SeasonMediaItem foundSeason = null;
					foreach (var season in serie.Seasons) {
						if (season == mediaToRemove) {
							foundSeason = season;
							break;
						}
						
						EpisodeMediaItem foundEpisode = null;
						foreach (var episode in season.Episodes) {
							if (episode == mediaToRemove) {
								foundEpisode = episode;
								break;
							}
						}

						if (foundEpisode!=null) {
							foundEpisode.ParentSeason.Episodes.Remove(foundEpisode);
							return true;
						}
					}
					
					if (foundSeason!=null) {
						serie.Seasons.Remove(foundSeason);
					}
				}
			}
			
			return false;
		}
		
		private static Entity.MediaItemBaseEntity CreateMediaItem(TreeNode node)
		{
			var guidStr = node.Tag as string;
			Entity.MediaItemBaseEntity mediaItem = null;
			
			if (!string.IsNullOrEmpty(guidStr))
			{
				var mve = mveEngine.Kernel.Instance.ItemCollection.ItemsList.Where(mveItem => mveItem.Id == guidStr).FirstOrDefault();
				mediaItem = CreateUiMediaItem(mve, node.Name);
				
				var childs = new List<Entity.MediaItemBaseEntity>();
				
				foreach (TreeNode item in node.Nodes) {
					childs.Add(CreateMediaItem(item));
				}
				
				var folder = mediaItem as Entity.FolderMediaItem;
				if (folder!=null) {
					foreach (var child in childs) {
						folder.ContentItems.Add(child);
					}
				}
				
				var serie = mediaItem as Entity.SerieMediaItem;
				if (serie!=null) {
					foreach (SeasonMediaItem child in childs.Where((m)=> {return m is SeasonMediaItem;} )) {
						var se = (SeasonMediaItem) child;
						se.ParentSerie = serie;
						serie.Seasons.Add(child as SeasonMediaItem);
					}
				}
				
				var season = mediaItem as Entity.SeasonMediaItem;
				if (season!=null) {
					foreach (var child in childs) {
						var episode = (EpisodeMediaItem) child;
						episode.ParentSeason = season;
						season.Episodes.Add(episode);
					}
				}
			}
			else
			{
				mediaItem = CreateUiMediaItem(null, node.Name);
				FolderMediaItem rootFolder = mediaItem as FolderMediaItem;
				
				if (rootFolder!=null) {
					foreach (var item in node.Nodes) {
						rootFolder.ContentItems.Add(CreateMediaItem((TreeNode)item));
					}
				}
			}
			
			return mediaItem;
		}
		
		private static Entity.MediaItemBaseEntity CreateUiMediaItem(mveEngine.Item mve, string name)
		{
			Entity.MediaItemBaseEntity mediaItem = null;
			
			if(mve==null)
			{
				return new FolderMediaItem()
				{
					Name = name
				};
			}
			
			switch (mve.Type)
			{
				case mveEngine.Entity.Movie:
					mediaItem = new MovieMediaItem()
					{
						Id =  new System.Guid(mve.Id)
					};
					break;
				case mveEngine.Entity.Series:
					mediaItem = new SerieMediaItem()
					{
						Id =  new System.Guid(mve.Id)
					};
					break;
				case mveEngine.Entity.Season:
					mediaItem = new SeasonMediaItem()
					{
						Id =  new System.Guid(mve.Id)
					};
					break;
				case mveEngine.Entity.Episode:
					mediaItem = new EpisodeMediaItem()
					{
						Id =  new System.Guid(mve.Id)
					};
					break;
				case mveEngine.Entity.Folder:
					mediaItem = new FolderMediaItem();
					break;
				default:
					break;
			}
			
			var video = mediaItem as VideoMediaElement;
			if (video!=null) {
				video.DataState = mve.DataState;
				video.Title = mve.Title;
				video.OriginalTitle = mve.OriginalTitle;
				video.SortTitle = mve.SortTitle;
				video.DateAdded = mve.DateAdded;
				video.Year = mve.Year;
				video.RunningTime = mve.RunningTime;
				video.Rating = mve.Rating;
				video.MPAARating = mve.MPAARating;
				video.Overview = mve.Overview;
				
				if (mve.Crew!=null) {
					foreach (var crew in mve.Crew) {
						video.CrewMembers.Add(crew.ToCrewMember());
					}
				}
				
				if (mve.Genres!=null) {
					foreach (var genre in mve.Genres) {
						video.Genres.Add(genre);
					}
				}
				
				if (mve.Actors!=null) {
					foreach (var actor in mve.Actors) {
						video.Actors.Add(actor.ToActorEntity());
					}
				}
				
				foreach (var p in mve.ImagesPaths) {
					video.Posters.Add(p.ToPosterEntity());
				}
				
				foreach (var p in mve.BackdropImagePaths) {
					video.Backdrops.Add(p.ToPosterEntity());
				}
				
				foreach (var p in mve.TrailerFiles) {
					video.Trailers.Add(new TrailerMediaItem()
					                   {
					                   	FilePath = p
					                   });
				}
				
				var movie = video as MovieMediaItem;
				if (movie!=null) {
					if (mve.PrimaryBackdrop!=null) {
						movie.PrimaryBackdrop = mve.PrimaryBackdrop.ToPosterEntity();
					}
				}
				
				var serie = video as SerieMediaItem;
				if (serie!=null) {
					serie.SeriesName = mve.SeriesName;
					
					if (mve.BannersPaths!=null) {
						foreach (var banner in mve.BannersPaths) {
							serie.Banners.Add(banner.ToPosterEntity());
						}
					}
					
					if (mve.PrimaryBanner!=null) {
						serie.PrimaryBanner = mve.PrimaryBanner.ToPosterEntity();
					}
					
					if (mve.PrimaryBackdrop!=null) {
						serie.PrimaryBackdrop = mve.PrimaryBackdrop.ToPosterEntity();
					}
					
					serie.PrimaryProviderId = mve.PrimaryProviderSerieId;
				}
				
				var season = video as SeasonMediaItem;
				if (season!=null) {
					season.SeasonNumber = mve.SeasonNumber;
				}
				
				if (mve.PrimaryImage!=null) {
					video.PrimaryPoster = mve.PrimaryImage.ToPosterEntity();
				}
				
				var episode = video as EpisodeMediaItem;
				if(episode != null)
				{
					episode.EpisodeNumber = mve.EpisodeNumber;
				}
				
			}
			else
			{
				mediaItem = new Entity.FolderMediaItem();
			}
			
			if (mediaItem!=null) {
				mediaItem.Name = name;
			}
			
			return mediaItem;
		}
	}
}